<?php

namespace support\register;

use app\services\TokenService;
use EasyWeChat\Factory;
use plugin\admin\app\model\User;
use support\Cache;
use Webman\Config;

class WechatMiniProgram extends CommonRegister
{
    public function ifExistsThenLogin($data)
    {
        $openId = $this->getOpenIdByCode($data['code']);

        $user = User::where('open_id', $openId)->first();

        if ($user) {
            return TokenService::generate($user['id']);
        }

        return false;
    }

    public function isExists($data)
    {
        $openId =  Cache::get('code-' . $data['code']);

        if (!$openId) {
            $openId = $this->getOpenIdByCode($data['code']);
        }

        return User::where('open_id', $openId)->count() > 0;
    }

    public function getOpenIdByCode($code)
    {
        $config = Config::get('wechat');
        $app = Factory::miniProgram($config);

        $loginRes = $app->auth->session($code);

        if (!$loginRes) {
            throw new \Exception('登录失败');
        }


        if (!isset($loginRes['openid'])) {
            throw new \Exception('获取openid失败');
        }

        Cache::set('code-' . $code, $loginRes['openid']);

        return $loginRes['openid'];
    }
}